<?php

/**
 * 分页类
 * @version 2013-04 崔俊涛
 */
class ExtendsYspPagerStudy {

    function urlAnalyze($page) {
        $url = $_SERVER['REQUEST_URI'];
        $parse_url = parse_url($url);
        $url_query = isset($parse_url['query']) ? $parse_url['query'] : '';
        if ($url_query) {
            if (strpos($url_query, 'page=') === false) {
                $url .= '&page=PAGE';
            } else {
                $url = str_replace('page=' . trim($page), 'page=PAGE', $url);
            }
        } else {
            $url .= '?page=PAGE';
        }
        return $url;
    }

    function getPager($total, $page, $pagesize) {
        $total_pages = ceil($total/$pagesize);
        $pageData = array();
        $pageData['pageCount'] = $total_pages;
        if (0 < $page - 1) {
            $pageData['prevPage'] = $page - 1;
        } else {
            $pageData['prevPage'] = 1;
        }
        if ($pageData['pageCount'] >= $page + 1) {
            $pageData['nextPage'] = $page + 1;
        } else {
            $pageData['nextPage'] = $page;
        }
        $pageData['lastPage'] = $pageData['pageCount'];

        $nextPageUrl = $this->urlAnalyze($page);

        $html = '<div class="pagerInfo" id="pagerInfo">';
        $html .= '<span>共' . $total . '条 ' . $page . '/' . $pageData['pageCount'] . '页</span>';
        $html .= '<a href="' . str_replace('PAGE', 1, $nextPageUrl) . '"><<</a>';
        $html .= '<a href="' . str_replace('PAGE', $pageData['prevPage'], $nextPageUrl) . '"><</a>';

        $p_start = 1;
        $p_end = 5;

        //前面的页码
        if ($page > 2) {
            if ($page >= $pageData['pageCount']) {
                $page = $pageData['pageCount'];
            }
            $p_start = $page - 2;
            $p_end = $page + 2;
        }

        if ($p_end - $pageData['pageCount'] > 0) {
            $p_end = $pageData['pageCount'];
        }

        for ($i = $p_start; $i <= $p_end; $i++) {
            if ($i == $page) {
                $html .= '<strong>' . $page . '</strong>';
            } elseif ($i > 0) {
                $html .= '<a href="' . str_replace('PAGE', $i, $nextPageUrl) . '">' . $i . '</a>';
            }
        }

        $html .= '<a href="' . str_replace('PAGE', $pageData['nextPage'], $nextPageUrl) . '">></a>';
        $html .= '<a href="' . str_replace('PAGE', $pageData['lastPage'], $nextPageUrl) . '">>></a>';
        $html .= '</div>';
        return $html;
    }

}